/**
 * @author: 子龙
 */
package com.fzl.lotterysystem.service.impl;

import com.fzl.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.fzl.lotterysystem.common.exception.ServiceException;
import com.fzl.lotterysystem.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class PictureServiceImpl implements PictureService {
    /**
     * 上传文件
     * @param multipartFile 上传文件的工具类
     * @return
     */
    @Value("${pic.local-path}")
    private  String localPath;

    @Override
    public String savePicture(MultipartFile multipartFile) {
        //创建目录
        File dir=new File(localPath);
        if(!dir.exists()){
            //可创建多级目录文件
            dir.mkdirs();
            //dir.mkdir();
        }

        //创建索引
        String fileName = multipartFile.getOriginalFilename();
        assert fileName != null;
        //截取最后一个点，拿到后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //生成·新的文件名
        fileName= UUID.randomUUID()+suffix;

        //图片保存
        try {
            multipartFile.transferTo(new File(localPath+"/"+fileName));
        } catch (IOException e) {
            throw new ServiceException(ServiceErrorCodeConstants.PIC_UPLOAD_ERROR);
        }
        return fileName;
    }
}